<?php
namespace classlib;
class request {
	/**
	 * 创建资料数字签名资料
	 * Enter description here ...
	 * @param array $data
	 * @return string
	 */
	public static function make_sign($data) {
		ksort($data);
		$sign  = implode('', $data);
		$sign  = md5($sign);
		return $sign;
	}
	
	/**
	 * 请求参数整合
	 * @param array $data
	 * @return string
	 */
	public static function querystr(&$data) {
		$params = array();
		foreach ($data as $key=>$value) {
			array_push($params, rawurlencode($key) . '=' . rawurlencode($value));
		}
		$querystr = implode('&', $params);
		return $querystr;
	}
		
	/**
	 * 发起Http请求
	 * @param string $url
	 * @param string $querystr
	 * @param array  $header
	 * @param string $method
	 * @param int    $timeout
	 * @param bool   $CA
	 * @return mix   $ret 错误返回array('code'=>errno, 'msg'=>error)
	 */
	public static function curl($url, $query, $header=array(), $method='POST', $timeout=15, $CA=FALSE) {
		$ssl   = (substr($url, 0, 8) == "https://")? true:false;
		$ch    = curl_init();
		if ('GET' == strtoupper($method)) {
			($query) && $url .='?'.$query;
			curl_setopt($ch, CURLOPT_URL, $url);
		} else {
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
		}
		if ($ssl && $CA) {
			$cacert = getcwd() . '/cacert.pem'; //CA根证书
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);   //只信任CA颁布的证书
			curl_setopt($ch, CURLOPT_CAINFO, $cacert); //CA根证书（用来验证的网站证书是否是CA颁布）
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //检查证书中是否设置域名，并且是否与提供的主机名匹配
		} else if ($ssl && !$CA) {
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //信任任何证书
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //检查证书中是否设置域名
		}
		$header[] = 'Expect:';
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		 
		$ret = curl_exec($ch);
		$err = curl_error($ch);
		$code= curl_getinfo($ch, CURLINFO_HTTP_CODE);
		if (($code != 200 && $code != 201) || false === $ret || !empty($err)) {
			$errno  = curl_errno($ch);
			error_log('url:'.$url."\r\n".'error:'.$err.';'.$errno."\r\n", 3, '/tmp/www-error.log');
			$ret    = false;
		}
		curl_close($ch);
		return $ret;
	}
	
	//完成请求执行代码逻辑
	public static function run($url, $query, $header=array(), $method='POST', $timeout=15, $CA=FALSE) {
		$res = self::curl($url, $query, $header, $method, $timeout, $CA);
		if (!$res) {
			return array('code'=>504, 'msg'=>'Web request exception, please try again');
		} else {
			return array('code'=>0, 'msg'=>$res);
		}
	}
}
